<!DOCTYPE HTML>
<html lang="zh-CN">
    

<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta name="keywords" content="Python GUI之tkinter窗口视窗教程大集合（看这篇就够了）, UESTC CV DeepLearning MachineLearning 洪卫 sunhw Hongwei 计算机视觉 深度学习">
    <meta name="baidu-site-verification" content="fmlEuI34ir">
    <meta name="google-site-verification" content="KeoTn_OFy4ndJwXNmm2gMeQfPhd7alqE9vQDwI32KCY">
    <meta name="description" content="一、前言
这篇文章是去年8月份学习python时顺便在博客园写的一篇笔记，现在搬运到hexo博客上来，主要针对新手。由于本篇文章较长，所以下面给出内容目录方便跳转阅读，当然也可以用博客页面最右侧的文章目录导航栏进行跳转查阅。
首次发布博客园">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Python GUI之tkinter窗口视窗教程大集合（看这篇就够了） | 洪卫の博客</title>
    <link rel="icon" type="image/jpeg" href="/favicon.jpg">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <!-- <link rel="stylesheet" type="text/css" href="/css/matery.css"> -->
    <!-- <link rel="stylesheet" type="text/css" href="/css/my.css"> -->
    <!-- <link rel="stylesheet" type="text/css" href="/libs/highlight/styles/atom-one-dark.css"> -->
    
    <!-- <style type="text/css">
        
            code[class*="language-"],
            pre[class*="language-"] {
                white-space: pre !important;
            }
        
    </style> -->

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
    <!-- 今日诗词 -->
    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
    
    <!-- 百度统计 洪卫  shw2018 add 2019.09.13 -->
    <script>
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?28c8c0fcedebccbf1e2bfc8b43c2e7b5";
          var s = document.getElementsByTagName("script")[0]; 
          s.parentNode.insertBefore(hm, s);
        })();
    </script>        
        
    <!-- 加入百度自动推送JS代码，全站激活，洪卫  shw2018 add 2019.08.13  -->
    
        <script>
            (function(){
                var bp = document.createElement('script');
                var curProtocol = window.location.protocol.split(':')[0];
                if (curProtocol === 'https') {
                    bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
                }
                else {
                    bp.src = 'http://push.zhanzhang.baidu.com/push.js';
                }
                var s = document.getElementsByTagName("script")[0];
                s.parentNode.insertBefore(bp, s);
            })();
        </script>
    

<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>


    <body>

        <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    <!-- 去掉 header 栏的 logo显示  洪卫 shw2018 2019.09.15-->
                    <!-- 
                    <img src="/favicon.jpg" class="logo-img" alt="LOGO">
                     -->
                    <span class="logo-span">洪卫の博客</span>
                </a>
            </div>
            


<!-- <a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/List" class="waves-effect waves-light">
            
            <i class="fa fa-heartbeat"></i>
            
            <span>清单</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/galleries" class="waves-effect waves-light">
            
            <i class="fa fa-photo"></i>
            
            <span>相册</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于我</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/contact" class="waves-effect waves-light">
            
            <i class="fa fa-envelope"></i>
            
            <span>留言板</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/navi" class="waves-effect waves-light">
            
            <i class="fa fa-rocket"></i>
            
            <span>快捷导航</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul> -->

<!-- 支持二级菜单特性 洪卫 shw2018 modify 2019.09.17  -->
<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right nav-menu">
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/" class="waves-effect waves-light">
              
                <i class="fa fa-home"></i>
              
              <span>首页</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
              <a href="/archives" class="waves-effect waves-light">
                
                  <i class="fa fa-archive"></i>
                
                <span>归档</span>
                <i class="fa fa-chevron-down" aria-hidden="true"></i>
              </a>

            <ul class="sub-nav menus_item_child ">
              
                <li> 
                  <a href="/categories" >
                    
                      <i class="fa fa-bookmark" style="margin-top: -20px;"></i>
                    
                    <span>分类</span>
                  </a>
                </li>
              
                <li> 
                  <a href="/categories/技术" >
                    
                      <i class="fa fa-code" style="margin-top: -20px;"></i>
                    
                    <span>技术</span>
                  </a>
                </li>
              
                <li> 
                  <a href="/categories/生活" >
                    
                      <i class="fa fa-file-text-o" style="margin-top: -20px;"></i>
                    
                    <span>生活</span>
                  </a>
                </li>
              
                <li> 
                  <a href="/categories/随想" >
                    
                      <i class="fa fa-commenting-o" style="margin-top: -20px;"></i>
                    
                    <span>随想</span>
                  </a>
                </li>
              
                <li> 
                  <a href="/categories/资源" >
                    
                      <i class="fa fa-cloud-download" style="margin-top: -20px;"></i>
                    
                    <span>资源</span>
                  </a>
                </li>
               
            </ul>
          
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
              <a href="/List" class="waves-effect waves-light">
                
                  <i class="fa fa-heartbeat"></i>
                
                <span>清单</span>
                <i class="fa fa-chevron-down" aria-hidden="true"></i>
              </a>

            <ul class="sub-nav menus_item_child ">
              
                <li> 
                  <a href="/List/music" >
                    
                      <i class="fa fa-music" style="margin-top: -20px;"></i>
                    
                    <span>音乐</span>
                  </a>
                </li>
              
                <li> 
                  <a href="/List/movies" >
                    
                      <i class="fa fa-film" style="margin-top: -20px;"></i>
                    
                    <span>视频</span>
                  </a>
                </li>
              
                <li> 
                  <a href="/books/" >
                    
                      <i class="fa fa-th-list faa-bounce" style="margin-top: -20px;"></i>
                    
                    <span>书单</span>
                  </a>
                </li>
              
                <li> 
                  <a href="/movies/" >
                    
                      <i class="fa fa-film faa-vertical" style="margin-top: -20px;"></i>
                    
                    <span>电影</span>
                  </a>
                </li>
               
            </ul>
          
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/galleries" class="waves-effect waves-light">
              
                <i class="fa fa-photo"></i>
              
              <span>相册</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/about" class="waves-effect waves-light">
              
                <i class="fa fa-user-circle-o"></i>
              
              <span>关于我</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/contact" class="waves-effect waves-light">
              
                <i class="fa fa-envelope"></i>
              
              <span>留言板</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/friends" class="waves-effect waves-light">
              
                <i class="fa fa-address-book"></i>
              
              <span>友情链接</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/navi" class="waves-effect waves-light">
              
                <i class="fa fa-rocket"></i>
              
              <span>快捷导航</span>
            </a>

            
      </li>
    

    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>

</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/favicon.jpg" class="logo-img circle responsive-img">
        
        <div class="logo-name">洪卫の博客</div>
        <div class="logo-desc">
            
            电子科技大学 | 电子与通信工程 | 计算机视觉
            
        </div>
    </div>

    

    <!-- <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/List" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-heartbeat"></i>
                
                清单
            </a>
        </li>
        
        <li>
            <a href="/galleries" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-photo"></i>
                
                相册
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于我
            </a>
        </li>
        
        <li>
            <a href="/contact" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-envelope"></i>
                
                留言板
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        <li>
            <a href="/navi" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-rocket"></i>
                
                快捷导航
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/shw2018/shw2018.github.io" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul> -->

<!-- 支持二级菜单特性 洪卫 shw2018 modify 2019.09.17  -->
<ul class="menu-list mobile-menu-list">
    
        <li class="m-nav-item">
                
                    <a href="/" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-home"></i>
                        
                        首页
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="javascript:;">
                            
                            <i class="fa fa-fw fa-archive"></i>
                            
                            归档
                            <span class="m-icon"><i class="fa fa-chevron-right"></i></span>
                    </a>
                <ul>
                  
                    <li> 
                      <a href="/categories" >
                           
                            <i class="fa fa-bookmark" style="left: 25px; position: absolute;"></i>
                       
                       <span>分类</span>
                      </a>
                    </li>
                  
                    <li> 
                      <a href="/categories/技术" >
                           
                            <i class="fa fa-code" style="left: 25px; position: absolute;"></i>
                       
                       <span>技术</span>
                      </a>
                    </li>
                  
                    <li> 
                      <a href="/categories/生活" >
                           
                            <i class="fa fa-file-text-o" style="left: 25px; position: absolute;"></i>
                       
                       <span>生活</span>
                      </a>
                    </li>
                  
                    <li> 
                      <a href="/categories/随想" >
                           
                            <i class="fa fa-commenting-o" style="left: 25px; position: absolute;"></i>
                       
                       <span>随想</span>
                      </a>
                    </li>
                  
                    <li> 
                      <a href="/categories/资源" >
                           
                            <i class="fa fa-cloud-download" style="left: 25px; position: absolute;"></i>
                       
                       <span>资源</span>
                      </a>
                    </li>
                   
                </ul>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="javascript:;">
                            
                            <i class="fa fa-fw fa-heartbeat"></i>
                            
                            清单
                            <span class="m-icon"><i class="fa fa-chevron-right"></i></span>
                    </a>
                <ul>
                  
                    <li> 
                      <a href="/List/music" >
                           
                            <i class="fa fa-music" style="left: 25px; position: absolute;"></i>
                       
                       <span>音乐</span>
                      </a>
                    </li>
                  
                    <li> 
                      <a href="/List/movies" >
                           
                            <i class="fa fa-film" style="left: 25px; position: absolute;"></i>
                       
                       <span>视频</span>
                      </a>
                    </li>
                  
                    <li> 
                      <a href="/books/" >
                           
                            <i class="fa fa-th-list faa-bounce" style="left: 25px; position: absolute;"></i>
                       
                       <span>书单</span>
                      </a>
                    </li>
                  
                    <li> 
                      <a href="/movies/" >
                           
                            <i class="fa fa-film faa-vertical" style="left: 25px; position: absolute;"></i>
                       
                       <span>电影</span>
                      </a>
                    </li>
                   
                </ul>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/galleries" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-photo"></i>
                        
                        相册
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/about" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-user-circle-o"></i>
                        
                        关于我
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/contact" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-envelope"></i>
                        
                        留言板
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/friends" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-address-book"></i>
                        
                        友情链接
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/navi" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-rocket"></i>
                        
                        快捷导航
                    </a>
              
            </li>
        

        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/shw2018/shw2018.github.io" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>

</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/shw2018/shw2018.github.io" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

        



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/9.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        Python GUI之tkinter窗口视窗教程大集合（看这篇就够了）
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px; /* 20px */
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Tutorial/" target="_blank">
                                <span class="chip bg-color">Tutorial</span>
                            </a>
                        
                            <a href="/tags/Python/" target="_blank">
                                <span class="chip bg-color">Python</span>
                            </a>
                        
                            <a href="/tags/GUI/" target="_blank">
                                <span class="chip bg-color">GUI</span>
                            </a>
                        
                            <a href="/tags/TKinter/" target="_blank">
                                <span class="chip bg-color">TKinter</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Python教程/" class="post-category" target="_blank">
                                Python教程
                            </a>
                        
                    </div>
                    
                </div>
            </div>
            
            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-08-16
                </div>

                
                    <div class="post-date info-break-policy">
                        <i class="fa fa-calendar-minus-o fa-fw"></i>更新日期:&nbsp;&nbsp;
                        2019-10-29
                    </div>
                

                <div class="post-author info-break-policy">
                    <i class="fa fa-user-o fa-fw"></i>作者:&nbsp;&nbsp;
                    
                        洪卫
                    
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>字数:&nbsp;&nbsp;
                        9.5k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>时长:&nbsp;&nbsp;
                        39 分钟
                    </div>
                    
                
                
                
                        <span id="busuanzi_container_site_pv" style='display:none'></span>
                        <i class="fa fa-eye fa-fw"></i>浏览量:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv" ></span>
    
                

            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="一、前言"><a href="#一、前言" class="headerlink" title="一、前言"></a>一、前言</h1><hr>
<p>这篇文章是去年8月份学习python时顺便在博客园写的一篇笔记，现在搬运到hexo博客上来，主要针对新手。由于本篇文章较长，所以下面给出内容目录方便跳转阅读，当然也可以用博客页面最右侧的文章目录导航栏进行跳转查阅。</p>
<p>首次发布博客园，原地址：<a href="https://www.cnblogs.com/shwee/p/9427975.html" target="_blank" rel="noopener">Python GUI之tkinter窗口视窗教程大集合（看这篇就够了）</a></p>
<ul>
<li><p>一、前言</p>
</li>
<li><p>二、Tkinter 是什么</p>
</li>
<li><p>三、Tkinter 控件详细介绍</p>
<ol>
<li>Tkinter 模块元素简要说明</li>
<li>常用窗口部件及简要说明：</li>
</ol>
</li>
<li><p>四、动手实践学习</p>
<ol>
<li>创建主窗口及Label部件（标签）创建使用</li>
<li>Button窗口部件</li>
<li>Entry窗口部件</li>
<li>Text窗口部件</li>
<li>Listbox窗口部件</li>
<li>Radiobutton窗口部件</li>
<li>Checkbutton窗口部件 </li>
<li>Scale窗口部件</li>
<li>Canvas窗口部件</li>
<li>Menu窗口部件</li>
<li>Frame 窗口部件</li>
<li>messageBox窗口部件</li>
<li>窗口部件三种放置方式pack/grid/place</li>
<li>综合练习，用户登录窗口例子</li>
<li>其他部件后续再补充…</li>
</ol>
</li>
</ul>
<h1 id="二、Tkinter是什么"><a href="#二、Tkinter是什么" class="headerlink" title="二、Tkinter是什么"></a>二、Tkinter是什么</h1><hr>
<p>Tkinter 是使用 python 进行窗口视窗设计的模块。Tkinter模块(“Tk 接口”)是Python的标准Tk GUI工具包的接口。作为 python 特定的GUI界面，是一个图像的窗口，tkinter是python 自带的，可以编辑的GUI界面，我们可以用GUI 实现很多直观的功能，比如想开发一个计算器，如果只是一个程序输入，输出窗口的话，是没用用户体验的。所有开发一个图像化的小窗口，就是必要的。</p>
<p>对于稍有GUI编程经验的人来说，Python的Tkinter界面库是非常简单的。python的GUI库非常多，选择`Tkinter，一是最为简单，二是自带库，不需下载安装，随时使用，三则是从需求出发，Python作为一种脚本语言，一种胶水语言，一般不会用它来开发复杂的桌面应用，它并不具备这方面的优势，使用Python，可以把它作为一个灵活的工具，而不是作为主要开发语言，那么在工作中，需要制作一个小工具，肯定是需要有界面的，不仅自己用，也能分享别人使用，在这种需求下，Tkinter是足够胜任的！</p>
<p>这篇文章主要做一个简单概述和实践编程，对于从没有接触过GUI的新手，在脑中树立一个基本的界面编程概念，同时自己也能学会如何简单的实现一些小的图形窗口功能。</p>
<p>对于Tkinter编程，可以用两个比喻来理解：</p>
<ul>
<li>第一个，作画。我们都见过美术生写生的情景，先支一个画架，放上画板，蒙上画布，构思内容，用铅笔画草图，组织结构和比例，调色板调色，最后画笔勾勒。相应的，对应到tkinter编程，那么我们的显示屏就是支起来的画架，根窗体就是画板，在tkinter中则是Toplevel，画布就是tkinter中的容器（Frame），画板上可以放很多张画布（Convas），tkinter中的容器中也可以放很多个容器，绘画中的构图布局则是tkinter中的布局管理器（几何管理器），绘画的内容就是tkinter中的一个个小组件，一幅画由许多元素构成，而我们的GUI界面，就是有一个个组件拼装起来的，它们就是widget。</li>
<li>第二个，我们小时候都玩过积木，只要发挥创意，相同的积木可以堆出各种造型。tkinter的组件也可以看做一个个积木，形状或许不同，其本质都是一样的，就是一个积木，不管它长什么样子，它始终就是积木！所以这些小组件都有许多共性，另外，个人认为，学习界面编程，最重要的不是一开始学习每个积木的样子，不是学习每个组件怎么用，而是这些组件该怎么放。初始学习中，怎么放远远比怎么用重要的多。网上有大量的文章资料，基本全是介绍组件怎么用的，对于怎么放，也就是tkinter中的布局管理器，都是一笔带过，这对初学者有点本末倒置，或许绝大部分是转载的原因吧，极少是自己真正写的。组件怎么用不是最迫切的，用到的时候再去了解也不迟，边用边学反而更好。因此我将专门写一章，详细介绍布局管理器的使用。</li>
</ul>
<h1 id="三、Tkinter-控件详细介绍"><a href="#三、Tkinter-控件详细介绍" class="headerlink" title="三、Tkinter 控件详细介绍"></a>三、Tkinter 控件详细介绍</h1><hr>
<p><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/1.png" alt=""></p>
<h2 id="1-Tkinter-模块元素简要说明"><a href="#1-Tkinter-模块元素简要说明" class="headerlink" title="1.Tkinter 模块元素简要说明"></a>1.Tkinter 模块元素简要说明</h2><hr>
<p><img src="1.png" alt=""><br>The Button Widget<br>The Canvas Widget<br>The Checkbutton Widget<br>The Entry Widget<br>The Frame Widget<br>The Label Widget<br>The LabelFrame Widget<br>The Listbox Widget<br>The Menu Widget<br>The Menubutton Widget<br>The Message Widget<br>The OptionMenu Widget<br>The PanedWindow Widget<br>The Radiobutton Widget<br>The Scale Widget<br>The Scrollbar Widget<br>The Spinbox Widget<br>The Text Widget<br>The Toplevel Widget<br>Basic Widget Methods<br>Toplevel Window Methods</p>
<h2 id="2-常用窗口部件及简要说明："><a href="#2-常用窗口部件及简要说明：" class="headerlink" title="2.常用窗口部件及简要说明："></a>2.常用窗口部件及简要说明：</h2><hr>
<p><code>Tkinter</code>支持<code>16</code>个核心的窗口部件，这个<code>16</code>个核心窗口部件类简要描述如下：</p>
<ul>
<li><code>Button</code>：一个简单的按钮，用来执行一个命令或别的操作</li>
<li><code>Canvas</code>：组织图形。这个部件可以用来绘制图表和图，创建图形编辑器，实现定制窗口部件。</li>
<li><code>Checkbutton</code>：代表一个变量，它有两个不同的值。点击这个按钮将会在这两个值间切换。</li>
<li><code>Entry</code>：文本输入域。</li>
<li><code>Frame</code>：一个容器窗口部件。帧可以有边框和背景，当创建一个应用程序或dialog(对话）版面时，帧被用来组织其它的窗口部件。</li>
<li><code>Label</code>：显示一个文本或图象。</li>
<li><code>Listbox</code>：显示供选方案的一个列表。listbox能够被配置来得到radiobutton或checklist的行为。</li>
<li><code>Menu</code>：菜单条。用来实现下拉和弹出式菜单。</li>
<li><code>Menubutton</code>：菜单按钮。用来实现下拉式菜单。</li>
<li><code>Message</code>：显示一文本。类似label窗口部件，但是能够自动地调整文本到给定的宽度或比率。</li>
<li><code>Radiobutton</code>：代表一个变量，它可以有多个值中的一个。点击它将为这个变量设置值，并且清除与这同一变量相关的其它radiobutton。</li>
<li><code>Scale</code>：允许你通过滑块来设置一数字值。</li>
<li><code>Scrollbar</code>：为配合使用canvas, entry, listbox, and text窗口部件的标准滚动条。</li>
<li><code>Text</code>：格式化文本显示。允许你用不同的样式和属性来显示和编辑文本。同时支持内嵌图象和窗口。</li>
<li><code>Toplevel</code>：一个容器窗口部件，作为一个单独的、最上面的窗口显示。</li>
<li><code>messageBox</code>：消息框，用于显示你应用程序的消息框。(Python2中为tkMessagebox)</li>
</ul>
<blockquote>
<p>注意在Tkinter中窗口部件类没有分级；所有的窗口部件类在树中都是兄弟关系。</p>
</blockquote>
<p>所有这些窗口部件提供了<code>Misc</code>和几何管理方法、配置管理方法和部件自己定义的另外的方法。此外，<code>Toplevel</code>类也提供窗口管理接口。这意味一个典型的窗口部件类提供了大约<code>150</code>种方法。</p>
<h1 id="四、动手实践学习"><a href="#四、动手实践学习" class="headerlink" title="四、动手实践学习"></a>四、动手实践学习</h1><hr>
<h2 id="1-创建主窗口及Label部件（标签）创建使用"><a href="#1-创建主窗口及Label部件（标签）创建使用" class="headerlink" title="1.创建主窗口及Label部件（标签）创建使用"></a>1.创建主窗口及Label部件（标签）创建使用</h2><hr>
<p>我们要学习使用上面提到的这些控件首先要创建一个主窗口，就像作画一样，先要架好架子和画板，然后才能在上面放画纸和各种绘画元素，创建好主窗口才能在上面放置各种控件元素。而创建过程是很简单的，如下：</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上设定标签</span>
l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'你好！this is Tkinter'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">30</span><span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 说明： bg为背景，font为字体，width为长，height为高，这里的长和高是字符的长和高，比如height=2,就是标签有2个字符这么高</span>

<span class="token comment" spellcheck="true"># 第5步，放置标签</span>
l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># Label内容content区域放置位置，自动调节尺寸</span>
<span class="token comment" spellcheck="true"># 放置lable的方法有：1）l.pack(); 2)l.place();</span>

<span class="token comment" spellcheck="true"># 第6步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 注意，loop因为是循环的意思，window.mainloop就会让window不断的刷新，如果没有mainloop,就是一个静态的window,传入进去的值就不会有循环，mainloop就相当于一个很大的while循环，有个while，每点击一次就会更新一次，所以我们必须要有循环</span>
<span class="token comment" spellcheck="true"># 所有的窗口文件都必须有类似的mainloop函数，mainloop是窗口文件的关键的关键。</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/2.png" alt=""></p>
<h2 id="2-Button窗口部件"><a href="#2-Button窗口部件" class="headerlink" title="2.Button窗口部件"></a>2.Button窗口部件</h2><hr>
<p>简单说明：</p>
<p>Button（按钮）部件是一个标准的Tkinter窗口部件，用来实现各种按钮。按钮能够包含文本或图象，并且你能够将按钮与一个Python函数或方法相关联。当这个按钮被按下时，Tkinter自动调用相关联的函数或方法。</p>
<p>按钮仅能显示一种字体，但是这个文本可以跨行。另外，这个文本中的一个字母可以有下划线，例如标明一个快捷键。默认情况，Tab键用于将焦点移动到一个按钮部件。</p>
<p>什么时候用按钮部件</p>
<p>简言之，按钮部件用来让用户说“马上给我执行这个任务”，通常我们用显示在按钮上的文本或图象来提示。按钮通常用在工具条中或应用程序窗口中，并且用来接收或忽略输入在对话框中的数据。关于按钮和输入的数据的配合，可以参看Checkbutton和Radiobutton部件。</p>
<p>如何创建：</p>
<p>普通的按钮很容易被创建，仅仅指定按钮的内容（文本、位图、图象）和一个当按钮被按下时的回调函数即可：</p>
<p>b = tk.Button(window, text=”hit me”, command=hit_me)</p>
<p>没有回调函数的按钮是没有用的，当你按下这个按钮时它什么也不做。你可能在开发一个应用程序的时候想实现这种按钮，比如为了不干扰你的beta版的测试者：</p>
<p>b = tk.Button(window, text=”Help”, command=DISABLED)</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上设定标签</span>
var <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 将label标签的内容设置为字符类型，用var来接收hit_me函数的传出内容用以显示在标签上</span>
l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> textvariable<span class="token operator">=</span>var<span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'white'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">30</span><span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 说明： bg为背景，fg为字体颜色，font为字体，width为长，height为高，这里的长和高是字符的长和高，比如height=2,就是标签有2个字符这么高</span>
l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 定义一个函数功能（内容自己自由编写），供点击Button按键时调用，调用命令参数command=函数名</span>
on_hit <span class="token operator">=</span> <span class="token boolean">False</span>
<span class="token keyword">def</span> <span class="token function">hit_me</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">global</span> on_hit
    <span class="token keyword">if</span> on_hit <span class="token operator">==</span> <span class="token boolean">False</span><span class="token punctuation">:</span>
        on_hit <span class="token operator">=</span> <span class="token boolean">True</span>
        var<span class="token punctuation">.</span>set<span class="token punctuation">(</span><span class="token string">'you hit me'</span><span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        on_hit <span class="token operator">=</span> <span class="token boolean">False</span>
        var<span class="token punctuation">.</span>set<span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，在窗口界面设置放置Button按键</span>
b <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'hit me'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> command<span class="token operator">=</span>hit_me<span class="token punctuation">)</span>
b<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/3.png" alt="图一"><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/4.png" alt="图二"> </p>
<h2 id="3-Entry窗口部件"><a href="#3-Entry窗口部件" class="headerlink" title="3. Entry窗口部件"></a>3. Entry窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Entry是tkinter类中提供的的一个单行文本输入域，用来输入显示一行文本，收集键盘输入(类似 HTML 中的 text)。</p>
<p>什么时候用：</p>
<p>需要用户输入用户信息时，比如我们平时使用软件、登录网页时，用户交互界面让我们登录账户信息等时候可以用到。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上设定输入框控件entry并放置控件</span>
e1 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window<span class="token punctuation">,</span> show<span class="token operator">=</span><span class="token string">'*'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 显示成密文形式</span>
e2 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window<span class="token punctuation">,</span> show<span class="token operator">=</span>None<span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 显示成明文形式</span>
e1<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
e2<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/5.png" alt=""></p>
<h2 id="4-Text窗口部件"><a href="#4-Text窗口部件" class="headerlink" title="4.Text窗口部件"></a>4.Text窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Text是tkinter类中提供的的一个多行文本区域，显示多行文本，可用来收集(或显示)用户输入的文字(类似 HTML 中的 textarea)，格式化文本显示，允许你用不同的样式和属性来显示和编辑文本，同时支持内嵌图象和窗口。</p>
<p>什么时候用：</p>
<p>在需要显示编辑用户、产品多行信息时，比如显示用户详细描述文字，产品简介等等，支持随时编辑。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上设定输入框控件entry框并放置</span>
e <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window<span class="token punctuation">,</span> show <span class="token operator">=</span> None<span class="token punctuation">)</span><span class="token comment" spellcheck="true">#显示成明文形式</span>
e<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，定义两个触发事件时的函数insert_point和insert_end（注意：因为Python的执行顺序是从上往下，所以函数一定要放在按钮的上面）</span>
<span class="token keyword">def</span> <span class="token function">insert_point</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment" spellcheck="true"># 在鼠标焦点处插入输入内容</span>
    var <span class="token operator">=</span> e<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span>
    t<span class="token punctuation">.</span>insert<span class="token punctuation">(</span><span class="token string">'insert'</span><span class="token punctuation">,</span> var<span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">insert_end</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>   <span class="token comment" spellcheck="true"># 在文本框内容最后接着插入输入内容</span>
    var <span class="token operator">=</span> e<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span>
    t<span class="token punctuation">.</span>insert<span class="token punctuation">(</span><span class="token string">'end'</span><span class="token punctuation">,</span> var<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，创建并放置两个按钮分别触发两种情况</span>
b1 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'insert point'</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span>
               height<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> command<span class="token operator">=</span>insert_point<span class="token punctuation">)</span>
b1<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
b2 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'insert end'</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span>
               height<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> command<span class="token operator">=</span>insert_end<span class="token punctuation">)</span>
b2<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，创建并放置一个多行文本框text用以显示，指定height=3为文本框是三个字符高度</span>
t <span class="token operator">=</span> tk<span class="token punctuation">.</span>Text<span class="token punctuation">(</span>window<span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">3</span><span class="token punctuation">)</span>
t<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第8步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/6.png" alt=""></p>
<h2 id="5-Listbox窗口部件"><a href="#5-Listbox窗口部件" class="headerlink" title="5.Listbox窗口部件"></a>5.Listbox窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Text是tkinter类中提供的的列表框部件，显示供选方案的一个列表。listbox能够被配置来得到radiobutton或checklist的行为。</p>
<p>什么时候用：</p>
<p>在有一个很多内容选项组成的列表提供用户选择时会用到。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建一个标签label用以显示并放置</span>
var1 <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 创建变量，用var1用来接收鼠标点击具体选项的内容</span>
l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'yellow'</span><span class="token punctuation">,</span>font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> textvariable<span class="token operator">=</span>var1<span class="token punctuation">)</span>
l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，创建一个方法用于按钮的点击事件</span>
<span class="token keyword">def</span> <span class="token function">print_selection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    value <span class="token operator">=</span> lb<span class="token punctuation">.</span>get<span class="token punctuation">(</span>lb<span class="token punctuation">.</span>curselection<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 获取当前选中的文本</span>
    var1<span class="token punctuation">.</span>set<span class="token punctuation">(</span>value<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 为label设置值</span>

<span class="token comment" spellcheck="true"># 第5步，创建一个按钮并放置，点击按钮调用print_selection函数</span>
b1 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'print selection'</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">15</span><span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> command<span class="token operator">=</span>print_selection<span class="token punctuation">)</span>
b1<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，创建Listbox并为其添加内容</span>
var2 <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>
var2<span class="token punctuation">.</span>set<span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 为变量var2设置值</span>
<span class="token comment" spellcheck="true"># 创建Listbox</span>
lb <span class="token operator">=</span> tk<span class="token punctuation">.</span>Listbox<span class="token punctuation">(</span>window<span class="token punctuation">,</span> listvariable<span class="token operator">=</span>var2<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true">#将var2的值赋给Listbox</span>
<span class="token comment" spellcheck="true"># 创建一个list并将值循环添加到Listbox控件中</span>
list_items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">11</span><span class="token punctuation">,</span><span class="token number">22</span><span class="token punctuation">,</span><span class="token number">33</span><span class="token punctuation">,</span><span class="token number">44</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> item <span class="token keyword">in</span> list_items<span class="token punctuation">:</span>
    lb<span class="token punctuation">.</span>insert<span class="token punctuation">(</span><span class="token string">'end'</span><span class="token punctuation">,</span> item<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 从最后一个位置开始加入值</span>
lb<span class="token punctuation">.</span>insert<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">'first'</span><span class="token punctuation">)</span>       <span class="token comment" spellcheck="true"># 在第一个位置加入'first'字符</span>
lb<span class="token punctuation">.</span>insert<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token string">'second'</span><span class="token punctuation">)</span>      <span class="token comment" spellcheck="true"># 在第二个位置加入'second'字符</span>
lb<span class="token punctuation">.</span>delete<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>                <span class="token comment" spellcheck="true"># 删除第二个位置的字符</span>
lb<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第8步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/7.png" alt=""></p>
<h2 id="6-Radiobutton窗口部件"><a href="#6-Radiobutton窗口部件" class="headerlink" title="6.Radiobutton窗口部件"></a>6.Radiobutton窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Radiobutton：代表一个变量，它可以有多个值中的一个。点击它将为这个变量设置值，并且清除与这同一变量相关的其它radiobutton。</p>
<p>什么时候用：</p>
<p>在有一个很多内容选项组成的选项列表提供用户选择时会用到，用户一次只能选择其中一个，不能多选。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建一个标签label用以显示并放置</span>
var <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 定义一个var用来将radiobutton的值和Label的值联系在一起.</span>
l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'yellow'</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">20</span><span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'empty'</span><span class="token punctuation">)</span>
l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，定义选项触发函数功能</span>
<span class="token keyword">def</span> <span class="token function">print_selection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    l<span class="token punctuation">.</span>config<span class="token punctuation">(</span>text<span class="token operator">=</span><span class="token string">'you have selected '</span> <span class="token operator">+</span> var<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，创建三个radiobutton选项，其中variable=var, value='A'的意思就是，当我们鼠标选中了其中一个选项，把value的值A放到变量var中，然后赋值给variable</span>
r1 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Radiobutton<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Option A'</span><span class="token punctuation">,</span> variable<span class="token operator">=</span>var<span class="token punctuation">,</span> value<span class="token operator">=</span><span class="token string">'A'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>print_selection<span class="token punctuation">)</span>
r1<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
r2 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Radiobutton<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Option B'</span><span class="token punctuation">,</span> variable<span class="token operator">=</span>var<span class="token punctuation">,</span> value<span class="token operator">=</span><span class="token string">'B'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>print_selection<span class="token punctuation">)</span>
r2<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
r3 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Radiobutton<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Option C'</span><span class="token punctuation">,</span> variable<span class="token operator">=</span>var<span class="token punctuation">,</span> value<span class="token operator">=</span><span class="token string">'C'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>print_selection<span class="token punctuation">)</span>
r3<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/8.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/9.png" alt=""></p>
<h2 id="7-Checkbutton窗口部件"><a href="#7-Checkbutton窗口部件" class="headerlink" title="7.Checkbutton窗口部件"></a>7.Checkbutton窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Checkbutton：代表一个变量，它有两个不同的值。点击这个按钮将会在这两个值间切换，选择和取消选择。</p>
<p>什么时候用：</p>
<p>在有一个很多内容选项组成的选项列表提供用户选择时会用到，用户一次可以选择多个。</p>
<p>**示例代码：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建一个标签label用以显示并放置</span>
l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'yellow'</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">20</span><span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'empty'</span><span class="token punctuation">)</span>
l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，定义触发函数功能</span>
<span class="token keyword">def</span> <span class="token function">print_selection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>var1<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span> <span class="token punctuation">(</span>var2<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">:</span>     <span class="token comment" spellcheck="true"># 如果选中第一个选项，未选中第二个选项</span>
        l<span class="token punctuation">.</span>config<span class="token punctuation">(</span>text<span class="token operator">=</span><span class="token string">'I love only Python '</span><span class="token punctuation">)</span>
    <span class="token keyword">elif</span> <span class="token punctuation">(</span>var1<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span> <span class="token punctuation">(</span>var2<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>   <span class="token comment" spellcheck="true"># 如果选中第二个选项，未选中第一个选项</span>
        l<span class="token punctuation">.</span>config<span class="token punctuation">(</span>text<span class="token operator">=</span><span class="token string">'I love only C++'</span><span class="token punctuation">)</span>
    <span class="token keyword">elif</span> <span class="token punctuation">(</span>var1<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span> <span class="token punctuation">(</span>var2<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">:</span>   <span class="token comment" spellcheck="true"># 如果两个选项都未选中</span>
        l<span class="token punctuation">.</span>config<span class="token punctuation">(</span>text<span class="token operator">=</span><span class="token string">'I do not love either'</span><span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        l<span class="token punctuation">.</span>config<span class="token punctuation">(</span>text<span class="token operator">=</span><span class="token string">'I love both'</span><span class="token punctuation">)</span>             <span class="token comment" spellcheck="true"># 如果两个选项都选中</span>

<span class="token comment" spellcheck="true"># 第5步，定义两个Checkbutton选项并放置</span>
var1 <span class="token operator">=</span> tk<span class="token punctuation">.</span>IntVar<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 定义var1和var2整型变量用来存放选择行为返回值</span>
var2 <span class="token operator">=</span> tk<span class="token punctuation">.</span>IntVar<span class="token punctuation">(</span><span class="token punctuation">)</span>
c1 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Checkbutton<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Python'</span><span class="token punctuation">,</span>variable<span class="token operator">=</span>var1<span class="token punctuation">,</span> onvalue<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> offvalue<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> command<span class="token operator">=</span>print_selection<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 传值原理类似于radiobutton部件</span>
c1<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
c2 <span class="token operator">=</span> tk<span class="token punctuation">.</span>Checkbutton<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'C++'</span><span class="token punctuation">,</span>variable<span class="token operator">=</span>var2<span class="token punctuation">,</span> onvalue<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> offvalue<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> command<span class="token operator">=</span>print_selection<span class="token punctuation">)</span>
c2<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/10.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/11.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/12.png" alt=""></p>
<h2 id="8-Scale窗口部件"><a href="#8-Scale窗口部件" class="headerlink" title="8.Scale窗口部件"></a>8.Scale窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Scale： 尺度（拉动条），允许你通过滑块来设置一数字值。</p>
<p>什么时候用：</p>
<p>在需要用户给出评价等级，或者给出一个评价分数，或者拉动滑动条提供一个具体的数值等等。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建一个标签label用以显示并放置</span>
l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'white'</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">20</span><span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'empty'</span><span class="token punctuation">)</span>
l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，定义一个触发函数功能</span>
<span class="token keyword">def</span> <span class="token function">print_selection</span><span class="token punctuation">(</span>v<span class="token punctuation">)</span><span class="token punctuation">:</span>
    l<span class="token punctuation">.</span>config<span class="token punctuation">(</span>text<span class="token operator">=</span><span class="token string">'you have selected '</span> <span class="token operator">+</span> v<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，创建一个尺度滑条，长度200字符，从0开始10结束，以2为刻度，精度为0.01，触发调用print_selection函数</span>
s <span class="token operator">=</span> tk<span class="token punctuation">.</span>Scale<span class="token punctuation">(</span>window<span class="token punctuation">,</span> label<span class="token operator">=</span><span class="token string">'try me'</span><span class="token punctuation">,</span> from_<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> to<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> orient<span class="token operator">=</span>tk<span class="token punctuation">.</span>HORIZONTAL<span class="token punctuation">,</span> length<span class="token operator">=</span><span class="token number">200</span><span class="token punctuation">,</span> showvalue<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span>tickinterval<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> resolution<span class="token operator">=</span><span class="token number">0.01</span><span class="token punctuation">,</span> command<span class="token operator">=</span>print_selection<span class="token punctuation">)</span>
s<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/13.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/14.png" alt=""></p>
<h2 id="9-Canvas窗口部件"><a href="#9-Canvas窗口部件" class="headerlink" title="9.Canvas窗口部件"></a>9.Canvas窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Canvas：画布，提供绘图功能(直线、椭圆、多边形、矩形) 可以包含图形或位图，用来绘制图表和图，创建图形编辑器，实现定制窗口部件。</p>
<p>什么时候用：</p>
<p>在比如像用户交互界面等，需要提供设计的图标、图形、logo等信息是可以用到画布。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建 500 * 200 大小的画布并放置各种元素</span>
canvas <span class="token operator">=</span> tk<span class="token punctuation">.</span>Canvas<span class="token punctuation">(</span>window<span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">200</span><span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">500</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 说明图片位置，并导入图片到画布上</span>
image_file <span class="token operator">=</span> tk<span class="token punctuation">.</span>PhotoImage<span class="token punctuation">(</span>file<span class="token operator">=</span><span class="token string">'pic.gif'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 图片位置（相对路径，与.py文件同一文件夹下，也可以用绝对路径，需要给定图片具体绝对路径）</span>
image <span class="token operator">=</span> canvas<span class="token punctuation">.</span>create_image<span class="token punctuation">(</span><span class="token number">250</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> anchor<span class="token operator">=</span><span class="token string">'n'</span><span class="token punctuation">,</span>image<span class="token operator">=</span>image_file<span class="token punctuation">)</span>        <span class="token comment" spellcheck="true"># 图片锚定点（n图片顶端的中间点位置）放在画布（250,0）坐标处</span>
<span class="token comment" spellcheck="true"># 定义多边形参数，然后在画布上画出指定图形</span>
x0<span class="token punctuation">,</span> y0<span class="token punctuation">,</span> x1<span class="token punctuation">,</span> y1 <span class="token operator">=</span> <span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">150</span><span class="token punctuation">,</span> <span class="token number">150</span>
line <span class="token operator">=</span> canvas<span class="token punctuation">.</span>create_line<span class="token punctuation">(</span>x0<span class="token number">-50</span><span class="token punctuation">,</span> y0<span class="token number">-50</span><span class="token punctuation">,</span> x1<span class="token number">-50</span><span class="token punctuation">,</span> y1<span class="token number">-50</span><span class="token punctuation">)</span>                   <span class="token comment" spellcheck="true"># 画直线</span>
oval <span class="token operator">=</span> canvas<span class="token punctuation">.</span>create_oval<span class="token punctuation">(</span>x0<span class="token operator">+</span><span class="token number">120</span><span class="token punctuation">,</span> y0<span class="token operator">+</span><span class="token number">50</span><span class="token punctuation">,</span> x1<span class="token operator">+</span><span class="token number">120</span><span class="token punctuation">,</span> y1<span class="token operator">+</span><span class="token number">50</span><span class="token punctuation">,</span> fill<span class="token operator">=</span><span class="token string">'yellow'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 画圆 用黄色填充</span>
arc <span class="token operator">=</span> canvas<span class="token punctuation">.</span>create_arc<span class="token punctuation">(</span>x0<span class="token punctuation">,</span> y0<span class="token operator">+</span><span class="token number">50</span><span class="token punctuation">,</span> x1<span class="token punctuation">,</span> y1<span class="token operator">+</span><span class="token number">50</span><span class="token punctuation">,</span> start<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> extent<span class="token operator">=</span><span class="token number">180</span><span class="token punctuation">)</span>      <span class="token comment" spellcheck="true"># 画扇形 从0度打开收到180度结束</span>
rect <span class="token operator">=</span> canvas<span class="token punctuation">.</span>create_rectangle<span class="token punctuation">(</span><span class="token number">330</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token number">330</span><span class="token operator">+</span><span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token operator">+</span><span class="token number">20</span><span class="token punctuation">)</span>                  <span class="token comment" spellcheck="true"># 画矩形正方形</span>
canvas<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，触发函数，用来一定指定图形</span>
<span class="token keyword">def</span> <span class="token function">moveit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    canvas<span class="token punctuation">.</span>move<span class="token punctuation">(</span>rect<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 移动正方形rect（也可以改成其他图形名字用以移动一起图形、元素），按每次（x=2, y=2）步长进行移动</span>

<span class="token comment" spellcheck="true"># 第5步，定义一个按钮用来移动指定图形的在画布上的位置</span>
b <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'move item'</span><span class="token punctuation">,</span>command<span class="token operator">=</span>moveit<span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>所用图片</strong>：</p>
<p>　　当然你可以随意用你的一张图片导入画布试一试效果，图片可以用画图工具改一下像素大小，以免图片太大，导入画布显示不全，当然你也可以用我提供的素材，下面是链接：<a href="https://files.cnblogs.com/files/shwee/pic.gif" target="_blank" rel="noopener">https://files.cnblogs.com/files/shwee/pic.gif</a> </p>
<p><img src="15.gif" alt=""></p>
<p><strong>图片锚定点位置参数图</strong>：<img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/16.png" alt=""></p>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/17.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/18.png" alt=""></p>
<h2 id="10-Menu窗口部件"><a href="#10-Menu窗口部件" class="headerlink" title="10.Menu窗口部件"></a>10.Menu窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Menu：菜单条，用来实现下拉和弹出式菜单，点下菜单后弹出的一个选项列表,用户可以从中选择</p>
<p>什么时候用：</p>
<p>在比如像软件或网页交互界面等，需要提供菜单选项功能提供用户选择菜单选项功能时用到。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建一个标签用以显示内容并放置</span>
l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'      '</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">)</span>
l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第10步，定义一个函数功能，用来代表菜单选项的功能，这里为了操作简单，定义的功能比较简单</span>
counter <span class="token operator">=</span> <span class="token number">0</span>
<span class="token keyword">def</span> <span class="token function">do_job</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">global</span> counter
    l<span class="token punctuation">.</span>config<span class="token punctuation">(</span>text<span class="token operator">=</span><span class="token string">'do '</span><span class="token operator">+</span> str<span class="token punctuation">(</span>counter<span class="token punctuation">)</span><span class="token punctuation">)</span>
    counter <span class="token operator">+=</span> <span class="token number">1</span>

<span class="token comment" spellcheck="true"># 第5步，创建一个菜单栏，这里我们可以把他理解成一个容器，在窗口的上方</span>
menubar <span class="token operator">=</span> tk<span class="token punctuation">.</span>Menu<span class="token punctuation">(</span>window<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，创建一个File菜单项（默认不下拉，下拉内容包括New，Open，Save，Exit功能项）</span>
filemenu <span class="token operator">=</span> tk<span class="token punctuation">.</span>Menu<span class="token punctuation">(</span>menubar<span class="token punctuation">,</span> tearoff<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 将上面定义的空菜单命名为File，放在菜单栏中，就是装入那个容器中</span>
menubar<span class="token punctuation">.</span>add_cascade<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'File'</span><span class="token punctuation">,</span> menu<span class="token operator">=</span>filemenu<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 在File中加入New、Open、Save等小菜单，即我们平时看到的下拉菜单，每一个小菜单对应命令操作。</span>
filemenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'New'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>do_job<span class="token punctuation">)</span>
filemenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Open'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>do_job<span class="token punctuation">)</span>
filemenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Save'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>do_job<span class="token punctuation">)</span>
filemenu<span class="token punctuation">.</span>add_separator<span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 添加一条分隔线</span>
filemenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Exit'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>window<span class="token punctuation">.</span>quit<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 用tkinter里面自带的quit()函数</span>

<span class="token comment" spellcheck="true"># 第7步，创建一个Edit菜单项（默认不下拉，下拉内容包括Cut，Copy，Paste功能项）</span>
editmenu <span class="token operator">=</span> tk<span class="token punctuation">.</span>Menu<span class="token punctuation">(</span>menubar<span class="token punctuation">,</span> tearoff<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 将上面定义的空菜单命名为 Edit，放在菜单栏中，就是装入那个容器中</span>
menubar<span class="token punctuation">.</span>add_cascade<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Edit'</span><span class="token punctuation">,</span> menu<span class="token operator">=</span>editmenu<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 同样的在 Edit 中加入Cut、Copy、Paste等小命令功能单元，如果点击这些单元, 就会触发do_job的功能</span>
editmenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Cut'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>do_job<span class="token punctuation">)</span>
editmenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Copy'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>do_job<span class="token punctuation">)</span>
editmenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Paste'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>do_job<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第8步，创建第二级菜单，即菜单项里面的菜单</span>
submenu <span class="token operator">=</span> tk<span class="token punctuation">.</span>Menu<span class="token punctuation">(</span>filemenu<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 和上面定义菜单一样，不过此处实在File上创建一个空的菜单</span>
filemenu<span class="token punctuation">.</span>add_cascade<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Import'</span><span class="token punctuation">,</span> menu<span class="token operator">=</span>submenu<span class="token punctuation">,</span> underline<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 给放入的菜单submenu命名为Import</span>

<span class="token comment" spellcheck="true"># 第9步，创建第三级菜单命令，即菜单项里面的菜单项里面的菜单命令（有点拗口，笑~~~）</span>
submenu<span class="token punctuation">.</span>add_command<span class="token punctuation">(</span>label<span class="token operator">=</span><span class="token string">'Submenu_1'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>do_job<span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 这里和上面创建原理也一样，在Import菜单项中加入一个小菜单命令Submenu_1</span>

<span class="token comment" spellcheck="true"># 第11步，创建菜单栏完成后，配置让菜单栏menubar显示出来</span>
window<span class="token punctuation">.</span>config<span class="token punctuation">(</span>menu<span class="token operator">=</span>menubar<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第12步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/19.gif" alt=""></p>
<h2 id="11-Frame-窗口部件"><a href="#11-Frame-窗口部件" class="headerlink" title="11.Frame 窗口部件"></a>11.Frame 窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>Frame：框架，用来承载放置其他GUI元素，就是一个容器，是一个在 Windows 上分离小区域的部件, 它能将 Windows 分成不同的区,然后存放不同的其他部件. 同时一个 Frame 上也能再分成两个 Frame, Frame 可以认为是一种容器.</p>
<p>什么时候用：</p>
<p>在比如像软件或网页交互界面等，有不同的界面逻辑层级和功能区域划分时可以用到，让交互界面逻辑更加清晰。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建一个标签用以显示内容并放置</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'on the window'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 和前面部件分开创建和放置不同，其实可以创建和放置一步完成</span>

<span class="token comment" spellcheck="true"># 第5步，创建一个主frame，长在主window窗口上</span>
frame <span class="token operator">=</span> tk<span class="token punctuation">.</span>Frame<span class="token punctuation">(</span>window<span class="token punctuation">)</span>
frame<span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，创建第二层框架frame，长在主框架frame上面</span>
frame_l <span class="token operator">=</span> tk<span class="token punctuation">.</span>Frame<span class="token punctuation">(</span>frame<span class="token punctuation">)</span><span class="token comment" spellcheck="true"># 第二层frame，左frame，长在主frame上</span>
frame_r <span class="token operator">=</span> tk<span class="token punctuation">.</span>Frame<span class="token punctuation">(</span>frame<span class="token punctuation">)</span><span class="token comment" spellcheck="true"># 第二层frame，右frame，长在主frame上</span>
frame_l<span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'left'</span><span class="token punctuation">)</span>
frame_r<span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'right'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，创建三组标签，为第二层frame上面的内容，分为左区域和右区域，用不同颜色标识</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>frame_l<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'on the frame_l1'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>frame_l<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'on the frame_l2'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>frame_l<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'on the frame_l3'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>frame_r<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'on the frame_r1'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'yellow'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>frame_r<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'on the frame_r2'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'yellow'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>frame_r<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'on the frame_r3'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'yellow'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第8步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/20.png" alt=""></p>
<h2 id="12-messageBox窗口部件"><a href="#12-messageBox窗口部件" class="headerlink" title="12.messageBox窗口部件"></a>12.messageBox窗口部件</h2><hr>
<p>简单说明：　　</p>
<p>messageBox：消息框，用于显示你应用程序的消息框。(Python2中为tkMessagebox)，其实这里的messageBox就是我们平时看到的弹窗。 我们首先需要定义一个触发功能，来触发这个弹窗，这里我们就放上以前学过的button按钮，通过触发功能，调用messagebox吧，点击button按钮就会弹出提示对话框。下面给出messagebox提示信息的几种形式：</p>
<pre class="line-numbers language-python"><code class="language-python">tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showinfo<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Hi'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'你好！'</span><span class="token punctuation">)</span>            <span class="token comment" spellcheck="true"># 提示信息对话窗</span>
tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showwarning<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Hi'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'有警告！'</span><span class="token punctuation">)</span>       <span class="token comment" spellcheck="true"># 提出警告对话窗</span>
tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showerror<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Hi'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'出错了！'</span><span class="token punctuation">)</span>         <span class="token comment" spellcheck="true"># 提出错误对话窗</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>askquestion<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Hi'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'你好！'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 询问选择对话窗return 'yes', 'no'</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>askyesno<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Hi'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'你好！'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>     <span class="token comment" spellcheck="true"># return 'True', 'False'</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>askokcancel<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Hi'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'你好！'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># return 'True', 'False'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>什么时候用：</p>
<p>在比如像软件或网页交互界面等，有不同的界面逻辑层级和功能区域划分时可以用到，让交互界面逻辑更加清晰。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>
<span class="token keyword">import</span> tkinter<span class="token punctuation">.</span>messagebox  <span class="token comment" spellcheck="true"># 要使用messagebox先要导入模块</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第5步，定义触发函数功能</span>
<span class="token keyword">def</span> <span class="token function">hit_me</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showinfo<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Hi'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'你好！'</span><span class="token punctuation">)</span>              <span class="token comment" spellcheck="true"># 提示信息对话窗</span>
    <span class="token comment" spellcheck="true"># tkinter.messagebox.showwarning(title='Hi', message='有警告！')       # 提出警告对话窗</span>
    <span class="token comment" spellcheck="true"># tkinter.messagebox.showerror(title='Hi', message='出错了！')         # 提出错误对话窗</span>
    <span class="token comment" spellcheck="true"># print(tkinter.messagebox.askquestion(title='Hi', message='你好！'))  # 询问选择对话窗return 'yes', 'no'</span>
    <span class="token comment" spellcheck="true"># print(tkinter.messagebox.askyesno(title='Hi', message='你好！'))     # return 'True', 'False'</span>
    <span class="token comment" spellcheck="true"># print(tkinter.messagebox.askokcancel(title='Hi', message='你好！'))  # return 'True', 'False'</span>

<span class="token comment" spellcheck="true"># 第4步，在图形界面上创建一个标签用以显示内容并放置</span>
tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'hit me'</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">,</span> command<span class="token operator">=</span>hit_me<span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/21.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/22.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/23.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/24.png" alt=""></p>
<h2 id="13-窗口部件三种放置方式pack-grid-place"><a href="#13-窗口部件三种放置方式pack-grid-place" class="headerlink" title="13.窗口部件三种放置方式pack/grid/place"></a>13.窗口部件三种放置方式pack/grid/place</h2><p><strong>参考来源</strong>：</p>
<ul>
<li><a href="http://effbot.org/tkinterbook/grid.htm" target="_blank" rel="noopener">The Grid Geometry Manager</a></li>
<li><a href="http://effbot.org/tkinterbook/pack.htm" target="_blank" rel="noopener">The Pack Geometry Manager</a></li>
<li><a href="http://effbot.org/tkinterbook/place.htm" target="_blank" rel="noopener">The Place Geometry Manager</a></li>
</ul>
<p><strong>1.Grid：The Grid Geometry Manager</strong>　　</p>
<p>grid 是方格, 所以所有的内容会被放在这些规律的方格中。例如：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> j <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span>grid<span class="token punctuation">(</span>row<span class="token operator">=</span>i<span class="token punctuation">,</span> column<span class="token operator">=</span>j<span class="token punctuation">,</span> padx<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> pady<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> ipadx<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> ipady<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>以上的代码就是创建一个三行三列的表格，其实 grid 就是用表格的形式定位的。这里的参数 row 为行，colum 为列，padx 就是单元格左右间距，pady 就是单元格上下间距，ipadx是单元格内部元素与单元格的左右间距，ipady是单元格内部元素与单元格的上下间距。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，grid 放置方法</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> j <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span>grid<span class="token punctuation">(</span>row<span class="token operator">=</span>i<span class="token punctuation">,</span> column<span class="token operator">=</span>j<span class="token punctuation">,</span> padx<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> pady<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> ipadx<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> ipady<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/25.png" alt=""></p>
<p><strong>2.Pack：The Pack Geometry Manager</strong></p>
<p>我们常用的pack(), 他会按照上下左右的方式排列.例如：</p>
<pre class="line-numbers language-python"><code class="language-python">tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'top'</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 上</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'bottom'</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 下</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'left'</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 左</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'right'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 右</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，pack 放置方法</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'top'</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 上</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'bottom'</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 下</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'left'</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 左</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'P'</span><span class="token punctuation">,</span> fg<span class="token operator">=</span><span class="token string">'red'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'right'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 右</span>

<span class="token comment" spellcheck="true"># 第5步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/26.png" alt=""></p>
<p><strong>3.Place：The Place Geometry Manager</strong></p>
<p>再接下来我们来看place(), 这个比较容易理解，就是给精确的坐标来定位，如此处给的(50, 100)，就是将这个部件放在坐标为(x=50, y=100)的这个位置, 后面的参数 anchor=’nw’，就是前面所讲的锚定点是西北角。例如：</p>
<pre class="line-numbers language-python"><code class="language-python">tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Pl'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token punctuation">)</span><span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">50</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">100</span><span class="token punctuation">,</span> anchor<span class="token operator">=</span><span class="token string">'nw'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'My Window'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'500x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，place 放置方法（精准的放置到指定坐标点的位置上）</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Pl'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token punctuation">)</span><span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">50</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">100</span><span class="token punctuation">,</span> anchor<span class="token operator">=</span><span class="token string">'nw'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/27.png" alt=""></p>
<h2 id="14-综合练习，用户登录窗口例子"><a href="#14-综合练习，用户登录窗口例子" class="headerlink" title="14.综合练习，用户登录窗口例子"></a>14.综合练习，用户登录窗口例子</h2><hr>
<p>编写一个用户登录界面，用户可以登录账户信息，如果账户已经存在，可以直接登录，登录名或者登录密码输入错误会提示，如果账户不存在，提示用户注册，点击注册进去注册页面，输入注册信息，确定后便可以返回登录界面进行登录。</p>
<p><strong>示例代码</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#!/usr/bin/env python</span>
<span class="token comment" spellcheck="true"># -*- coding: utf-8 -*-</span>
<span class="token comment" spellcheck="true"># author:洪卫</span>

<span class="token keyword">import</span> tkinter <span class="token keyword">as</span> tk  <span class="token comment" spellcheck="true"># 使用Tkinter前需要先导入</span>
<span class="token keyword">import</span> tkinter<span class="token punctuation">.</span>messagebox
<span class="token keyword">import</span> pickle

<span class="token comment" spellcheck="true"># 第1步，实例化object，建立窗口window</span>
window <span class="token operator">=</span> tk<span class="token punctuation">.</span>Tk<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第2步，给窗口的可视化起名字</span>
window<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'Wellcome to Hongwei Website'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第3步，设定窗口的大小(长 * 宽)</span>
window<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'400x300'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 这里的乘是小x</span>

<span class="token comment" spellcheck="true"># 第4步，加载 wellcome image</span>
canvas <span class="token operator">=</span> tk<span class="token punctuation">.</span>Canvas<span class="token punctuation">(</span>window<span class="token punctuation">,</span> width<span class="token operator">=</span><span class="token number">400</span><span class="token punctuation">,</span> height<span class="token operator">=</span><span class="token number">135</span><span class="token punctuation">,</span> bg<span class="token operator">=</span><span class="token string">'green'</span><span class="token punctuation">)</span>
image_file <span class="token operator">=</span> tk<span class="token punctuation">.</span>PhotoImage<span class="token punctuation">(</span>file<span class="token operator">=</span><span class="token string">'pic.gif'</span><span class="token punctuation">)</span>
image <span class="token operator">=</span> canvas<span class="token punctuation">.</span>create_image<span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> anchor<span class="token operator">=</span><span class="token string">'n'</span><span class="token punctuation">,</span> image<span class="token operator">=</span>image_file<span class="token punctuation">)</span>
canvas<span class="token punctuation">.</span>pack<span class="token punctuation">(</span>side<span class="token operator">=</span><span class="token string">'top'</span><span class="token punctuation">)</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Wellcome'</span><span class="token punctuation">,</span>font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>pack<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第5步，用户信息</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'User name:'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">170</span><span class="token punctuation">)</span>
tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Password:'</span><span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">210</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第6步，用户登录输入框entry</span>
<span class="token comment" spellcheck="true"># 用户名</span>
var_usr_name <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>
var_usr_name<span class="token punctuation">.</span>set<span class="token punctuation">(</span><span class="token string">'example@python.com'</span><span class="token punctuation">)</span>
entry_usr_name <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window<span class="token punctuation">,</span> textvariable<span class="token operator">=</span>var_usr_name<span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
entry_usr_name<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">120</span><span class="token punctuation">,</span>y<span class="token operator">=</span><span class="token number">175</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 用户密码</span>
var_usr_pwd <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>
entry_usr_pwd <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window<span class="token punctuation">,</span> textvariable<span class="token operator">=</span>var_usr_pwd<span class="token punctuation">,</span> font<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">'Arial'</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">)</span><span class="token punctuation">,</span> show<span class="token operator">=</span><span class="token string">'*'</span><span class="token punctuation">)</span>
entry_usr_pwd<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">120</span><span class="token punctuation">,</span>y<span class="token operator">=</span><span class="token number">215</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第8步，定义用户登录功能</span>
<span class="token keyword">def</span> <span class="token function">usr_login</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 这两行代码就是获取用户输入的usr_name和usr_pwd</span>
    usr_name <span class="token operator">=</span> var_usr_name<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span>
    usr_pwd <span class="token operator">=</span> var_usr_pwd<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 这里设置异常捕获，当我们第一次访问用户信息文件时是不存在的，所以这里设置异常捕获。</span>
    <span class="token comment" spellcheck="true"># 中间的两行就是我们的匹配，即程序将输入的信息和文件中的信息匹配。</span>
    <span class="token keyword">try</span><span class="token punctuation">:</span>
        <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'usrs_info.pickle'</span><span class="token punctuation">,</span> <span class="token string">'rb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> usr_file<span class="token punctuation">:</span>
            usrs_info <span class="token operator">=</span> pickle<span class="token punctuation">.</span>load<span class="token punctuation">(</span>usr_file<span class="token punctuation">)</span>
    <span class="token keyword">except</span> FileNotFoundError<span class="token punctuation">:</span>
        <span class="token comment" spellcheck="true"># 这里就是我们在没有读取到`usr_file`的时候，程序会创建一个`usr_file`这个文件，并将管理员</span>
        <span class="token comment" spellcheck="true"># 的用户和密码写入，即用户名为`admin`密码为`admin`。</span>
        <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'usrs_info.pickle'</span><span class="token punctuation">,</span> <span class="token string">'wb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> usr_file<span class="token punctuation">:</span>
            usrs_info <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token string">'admin'</span><span class="token punctuation">:</span> <span class="token string">'admin'</span><span class="token punctuation">}</span>
            pickle<span class="token punctuation">.</span>dump<span class="token punctuation">(</span>usrs_info<span class="token punctuation">,</span> usr_file<span class="token punctuation">)</span>
            usr_file<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 必须先关闭，否则pickle.load()会出现EOFError: Ran out of input</span>

    <span class="token comment" spellcheck="true"># 如果用户名和密码与文件中的匹配成功，则会登录成功，并跳出弹窗how are you? 加上你的用户名。</span>
    <span class="token keyword">if</span> usr_name <span class="token keyword">in</span> usrs_info<span class="token punctuation">:</span>
        <span class="token keyword">if</span> usr_pwd <span class="token operator">==</span> usrs_info<span class="token punctuation">[</span>usr_name<span class="token punctuation">]</span><span class="token punctuation">:</span>
            tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showinfo<span class="token punctuation">(</span>title<span class="token operator">=</span><span class="token string">'Welcome'</span><span class="token punctuation">,</span> message<span class="token operator">=</span><span class="token string">'How are you? '</span> <span class="token operator">+</span> usr_name<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 如果用户名匹配成功，而密码输入错误，则会弹出'Error, your password is wrong, try again.'</span>
        <span class="token keyword">else</span><span class="token punctuation">:</span>
            tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showerror<span class="token punctuation">(</span>message<span class="token operator">=</span><span class="token string">'Error, your password is wrong, try again.'</span><span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>  <span class="token comment" spellcheck="true"># 如果发现用户名不存在</span>
        is_sign_up <span class="token operator">=</span> tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>askyesno<span class="token punctuation">(</span><span class="token string">'Welcome！ '</span><span class="token punctuation">,</span> <span class="token string">'You have not sign up yet. Sign up now?'</span><span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 提示需不需要注册新用户</span>
        <span class="token keyword">if</span> is_sign_up<span class="token punctuation">:</span>
            usr_sign_up<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第9步，定义用户注册功能</span>
<span class="token keyword">def</span> <span class="token function">usr_sign_up</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">sign_to_Hongwei_Website</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token comment" spellcheck="true"># 以下三行就是获取我们注册时所输入的信息</span>
        np <span class="token operator">=</span> new_pwd<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span>
        npf <span class="token operator">=</span> new_pwd_confirm<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span>
        nn <span class="token operator">=</span> new_name<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">)</span>

        <span class="token comment" spellcheck="true"># 这里是打开我们记录数据的文件，将注册信息读出</span>
        <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'usrs_info.pickle'</span><span class="token punctuation">,</span> <span class="token string">'rb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> usr_file<span class="token punctuation">:</span>
            exist_usr_info <span class="token operator">=</span> pickle<span class="token punctuation">.</span>load<span class="token punctuation">(</span>usr_file<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 这里就是判断，如果两次密码输入不一致，则提示Error, Password and confirm password must be the same!</span>
        <span class="token keyword">if</span> np <span class="token operator">!=</span> npf<span class="token punctuation">:</span>
            tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showerror<span class="token punctuation">(</span><span class="token string">'Error'</span><span class="token punctuation">,</span> <span class="token string">'Password and confirm password must be the same!'</span><span class="token punctuation">)</span>

        <span class="token comment" spellcheck="true"># 如果用户名已经在我们的数据文件中，则提示Error, The user has already signed up!</span>
        <span class="token keyword">elif</span> nn <span class="token keyword">in</span> exist_usr_info<span class="token punctuation">:</span>
            tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showerror<span class="token punctuation">(</span><span class="token string">'Error'</span><span class="token punctuation">,</span> <span class="token string">'The user has already signed up!'</span><span class="token punctuation">)</span>

        <span class="token comment" spellcheck="true"># 最后如果输入无以上错误，则将注册输入的信息记录到文件当中，并提示注册成功Welcome！,You have successfully signed up!，然后销毁窗口。</span>
        <span class="token keyword">else</span><span class="token punctuation">:</span>
            exist_usr_info<span class="token punctuation">[</span>nn<span class="token punctuation">]</span> <span class="token operator">=</span> np
            <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'usrs_info.pickle'</span><span class="token punctuation">,</span> <span class="token string">'wb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> usr_file<span class="token punctuation">:</span>
                pickle<span class="token punctuation">.</span>dump<span class="token punctuation">(</span>exist_usr_info<span class="token punctuation">,</span> usr_file<span class="token punctuation">)</span>
            tkinter<span class="token punctuation">.</span>messagebox<span class="token punctuation">.</span>showinfo<span class="token punctuation">(</span><span class="token string">'Welcome'</span><span class="token punctuation">,</span> <span class="token string">'You have successfully signed up!'</span><span class="token punctuation">)</span>
            <span class="token comment" spellcheck="true"># 然后销毁窗口。</span>
            window_sign_up<span class="token punctuation">.</span>destroy<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 定义长在窗口上的窗口</span>
    window_sign_up <span class="token operator">=</span> tk<span class="token punctuation">.</span>Toplevel<span class="token punctuation">(</span>window<span class="token punctuation">)</span>
    window_sign_up<span class="token punctuation">.</span>geometry<span class="token punctuation">(</span><span class="token string">'300x200'</span><span class="token punctuation">)</span>
    window_sign_up<span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token string">'Sign up window'</span><span class="token punctuation">)</span>

    new_name <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 将输入的注册名赋值给变量</span>
    new_name<span class="token punctuation">.</span>set<span class="token punctuation">(</span><span class="token string">'example@python.com'</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 将最初显示定为'example@python.com'</span>
    tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window_sign_up<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'User name: '</span><span class="token punctuation">)</span><span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 将`User name:`放置在坐标（10,10）。</span>
    entry_new_name <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window_sign_up<span class="token punctuation">,</span> textvariable<span class="token operator">=</span>new_name<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 创建一个注册名的`entry`，变量为`new_name`</span>
    entry_new_name<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">130</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># `entry`放置在坐标（150,10）.</span>

    new_pwd <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>
    tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window_sign_up<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Password: '</span><span class="token punctuation">)</span><span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">50</span><span class="token punctuation">)</span>
    entry_usr_pwd <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window_sign_up<span class="token punctuation">,</span> textvariable<span class="token operator">=</span>new_pwd<span class="token punctuation">,</span> show<span class="token operator">=</span><span class="token string">'*'</span><span class="token punctuation">)</span>
    entry_usr_pwd<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">130</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">50</span><span class="token punctuation">)</span>

    new_pwd_confirm <span class="token operator">=</span> tk<span class="token punctuation">.</span>StringVar<span class="token punctuation">(</span><span class="token punctuation">)</span>
    tk<span class="token punctuation">.</span>Label<span class="token punctuation">(</span>window_sign_up<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Confirm password: '</span><span class="token punctuation">)</span><span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">90</span><span class="token punctuation">)</span>
    entry_usr_pwd_confirm <span class="token operator">=</span> tk<span class="token punctuation">.</span>Entry<span class="token punctuation">(</span>window_sign_up<span class="token punctuation">,</span> textvariable<span class="token operator">=</span>new_pwd_confirm<span class="token punctuation">,</span> show<span class="token operator">=</span><span class="token string">'*'</span><span class="token punctuation">)</span>
    entry_usr_pwd_confirm<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">130</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">90</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 下面的 sign_to_Hongwei_Website</span>
    btn_comfirm_sign_up <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window_sign_up<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Sign up'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>sign_to_Hongwei_Website<span class="token punctuation">)</span>
    btn_comfirm_sign_up<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">180</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">120</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第7步，login and sign up 按钮</span>
btn_login <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Login'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>usr_login<span class="token punctuation">)</span>
btn_login<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">120</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">240</span><span class="token punctuation">)</span>
btn_sign_up <span class="token operator">=</span> tk<span class="token punctuation">.</span>Button<span class="token punctuation">(</span>window<span class="token punctuation">,</span> text<span class="token operator">=</span><span class="token string">'Sign up'</span><span class="token punctuation">,</span> command<span class="token operator">=</span>usr_sign_up<span class="token punctuation">)</span>
btn_sign_up<span class="token punctuation">.</span>place<span class="token punctuation">(</span>x<span class="token operator">=</span><span class="token number">200</span><span class="token punctuation">,</span> y<span class="token operator">=</span><span class="token number">240</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 第10步，主窗口循环显示</span>
window<span class="token punctuation">.</span>mainloop<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>测试效果</strong>：<br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/28.png" alt=""><br><img src="https://raw.githubusercontent.com/shw2018/cdn/master/blog_files/img/Python-GUI-TKinter-Tutorial/29.png" alt=""></p>
<h2 id="15-其他部件后续再补充…"><a href="#15-其他部件后续再补充…" class="headerlink" title="15.其他部件后续再补充…"></a>15.其他部件后续再补充…</h2><hr>
<blockquote>
<p>注：不同电脑可能配置环境略有不同，如有小错误可以自己调试一下。</p>
</blockquote>
<script>
        document.querySelectorAll('.github-emoji')
          .forEach(el => {
            if (!el.dataset.src) { return; }
            const img = document.createElement('img');
            img.style = 'display:none !important;';
            img.src = el.dataset.src;
            img.addEventListener('error', () => {
              img.remove();
              el.style.color = 'inherit';
              el.style.backgroundImage = 'none';
              el.style.background = 'none';
            });
            img.addEventListener('load', () => {
              img.remove();
            });
            document.body.appendChild(img);
          });
      </script>
            </div>
            <hr/>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力!</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.bmp" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.bmp" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fa fa-user">
                        作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://sunhwee.com" rel="external nofollow noreferrer">洪卫</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fa fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://sunhwee.com/posts/80fa3a85.html">https://sunhwee.com/posts/80fa3a85.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fa fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://sunhwee.com" target="_blank">洪卫</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <!-- 
            <div class="reprint1">
                <p>
                    <span class="reprint1-tip">
                        <i class="fa fa-exclamation-circle"></i>&nbsp;&nbsp;版权声明:
                    </span>
                    <a href="https://sunhwee.com" class="b-link-green">洪卫の博客</a>
                    <i class="fa fa-angle-right fa-lg fa-fw text-color"></i>
                    <a href="/posts/80fa3a85.html" class="b-link-green">Python GUI之tkinter窗口视窗教程大集合（看这篇就够了）</a>
                </p>
            </div> -->
            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Tutorial/">
                                    <span class="chip bg-color">Tutorial</span>
                                </a>
                            
                                <a href="/tags/Python/">
                                    <span class="chip bg-color">Python</span>
                                </a>
                            
                                <a href="/tags/GUI/">
                                    <span class="chip bg-color">GUI</span>
                                </a>
                            
                                <a href="/tags/TKinter/">
                                    <span class="chip bg-color">TKinter</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <!-- <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css"> -->
<!-- <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div> -->

<!-- <script src="/libs/share/js/social-share.min.js"></script> -->
<!-- <script src="/libs/share/js/social-share.min.js"></script> -->

<link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'ffe0ea359d9892dfbadb',
        clientSecret: '765e3f453b6537e292b3f4132db5bda05d18bffc',
        repo: 'shw2018.github.io',
        owner: 'shw2018',
        admin: ["shw2018"],
        id: 'posts/80fa3a85.html',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }
    /* valine 评论框增加背景图片 */
    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments input[type=text],
    #vcomments input[type=email],
    #vcomments input[type=url],
    #vcomments textarea {
        box-sizing: border-box;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #42b983;
        font-weight: 500;
        /* text-decoration: underline; */
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    /* 修复评论第一行位置错位 */
    .v .vlist .vcard {
    padding-top: 2.5em !important ;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div id="vcomments" class="card-content"></div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="/libs//libs/jQuery-emoji/dist/css/jquery.emoji.css">
<script src="/libs//libs/jQuery-emoji/dist/js/jquery.emoji.min.js"></script>
<script src="/libs//libs/jQuery-emoji/dist/js/emoji.list.js"></script> -->
<script>
    new Valine({
        el: '#vcomments',
        appId: 'lLPMWOb3ctIegVovkXFVQHVz-gzGzoHsz',
        appKey: 'rR3LIiSBOYukuM3gLpL76rQt',
        notify: 'true' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'https://s.gravatar.com/avatar/0007991f99268c04f1aa4cdd9bea93b4?s=80',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: '没有Github账号的在这里留言评论～',

    });

//     function parse_emoji() {
//     jQuery(".vcontent").emojiParse({
//       basePath: '/libs/jQuery-emoji/images/emoji',
//       icons: emojiLists   // 注：详见 js/emoji.list.js
//     });
//   }
  
//   setTimeout(function() {
//     // jQuery emoji 解析
//     parse_emoji();
//     // jquery emoji 初始化
//     jQuery(".veditor").emoji({
//       showTab: true,
//       animation: 'slide',
//       basePath: '/libs/jQuery-emoji/images/emoji',
//       icons: emojiLists  // 注：详见 js/emoji.list.js
//     });
//     jQuery(".vmore").on("click", function() {
//       setTimeout(function() {
//         parse_emoji();
//       }, 500);
//     });
//   }, 800)

</script>
    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/a927e90e.html">
                    <div class="card-image">
                        
                        <img src="/medias/banner/10.jpg" class="responsive-img" alt="Markdown Emoji表情语法速查表">
                        
                        <span class="card-title">Markdown Emoji表情语法速查表</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            这是一篇关于markdown中快速插入Emoji表情的语法速查表，以后写markdown想要插入emoji表情忘记语法了，可以快速查看，挺方便的。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-08-16
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/文章写作技巧/" class="post-category" target="_blank">
                                    文章写作技巧
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Markdown/" target="_blank">
                        <span class="chip bg-color">Markdown</span>
                    </a>
                    
                    <a href="/tags/Emoji/" target="_blank">
                        <span class="chip bg-color">Emoji</span>
                    </a>
                    
                    <a href="/tags/表情包/" target="_blank">
                        <span class="chip bg-color">表情包</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/7e1e06e9.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/10.jpg" class="responsive-img" alt="Markdown 常用语法">
                        
                        <span class="card-title">Markdown 常用语法</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            1. Markdown 插入图片的几种方法1.1 原 markdown 语法![这是图片描述](这是图片链接)
1.2 html 语法&lt;p align="center">&lt;img src="https://raw.githubu
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-08-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/写作技巧/" class="post-category" target="_blank">
                                    写作技巧
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Markdown/" target="_blank">
                        <span class="chip bg-color">Markdown</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 洪卫の博客<br />'
            + '作者: 洪卫<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- shw2018 洪卫 add 2019.10.15 -->
<!-- 代码块功能依赖 -->

    <script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>
    
    
    <!-- 代码语言 -->
    
    <script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>
    
        
    <!-- 代码块复制 -->
    
    <script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>
    <script type="text/javascript" src="/libs/codeBlock/clipboard.min.js"></script>
    
    
    <!-- 代码块收缩 -->
    
    <script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>
    
    
    <!-- 代码块折行 -->
    
    <style type="text/css">
    code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
    </style>
    
    
    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <!-- <a class="btn-floating btn-large bg-color"> -->
    <a class="btn-floating btn-large ">    <!-- 去掉按键 bg-color  洪卫 shw2018 modify 2019.09.13-->
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h1, h2, h3, h4, h5'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


        <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&copy; 2019 Hongwei. <span class="with-love" id="heart"><i class="fa fa-heart" style="color:#ff71a8"></i> </span> 渝ICP备19012360号

            <br>
            <span id="sitetime"></span><span class="my-face">ღゝ◡╹)ノ♡</span>
            <br>

            

            
                    
                        <span id="busuanzi_container_site_pv" style='display:none'></span>
                        总访问量: <span id="busuanzi_value_site_pv" class="white-color"></span>
                    
        
                    
                        <span id="busuanzi_container_site_uv" style='display:none'></span>
                        人次&nbsp; | &nbsp;访客人数: <span id="busuanzi_value_site_uv" class="white-color"></span> 人
                    
    
            

            
                &nbsp; | &nbsp;字数统计:&nbsp;
                <span class="white-color">75.7k</span> 字
            

            
            <br>

            <!-- 友盟站点统计 洪卫 shw2018 add 2019.09.12  -->
            <script type="text/javascript">
                var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
                document.write(unescape("%3Cspan id='cnzz_stat_icon_1278019489'%3E%3C/span%3E%3Cscript src='" +
                    cnzz_protocol +
                    "s9.cnzz.com/z_stat.php%3Fid%3D1278019489%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"
                    ));
            </script>

        </div>

        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/shw2018" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>


 
    <a href="https://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=948840751@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>




    <a href="https://zhihu.com/people/hongwei-60-34" class="tooltipped" target="_blank" data-tooltip="访问我的知乎" data-position="top" data-delay="50">
        <i class="fa fa-inverse">知</i>
    </a>



    <a href="http://wpa.qq.com/msgrd?v=3&uin=948840751&site=qq&menu=yes" class="tooltipped" target="_blank" data-tooltip="访问我的QQ空间" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>



    <a href="https://weibo.com/3010027571" class="tooltipped" target="_blank" data-tooltip="关注我的微博" data-position="top" data-delay="50">
        <i class="fa fa-weibo"></i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>

    </div>
</footer>

<div class="progress-bar"></div>

<!-- 不蒜子计数初始值纠正 -->
<script>
    $(document).ready(function () {

        var int = setInterval(fixCount, 50);
        var pvcountOffset = 10000;
        var uvcountOffset = 4000;

        function fixCount() {
            if (document.getElementById("busuanzi_container_site_pv").style.display != "none") {
                $("#busuanzi_value_site_pv").html(parseInt($("#busuanzi_value_site_pv").html()) +
                    pvcountOffset);
                clearInterval(int);
            }
            if ($("#busuanzi_container_site_pv").css("display") != "none") {
                $("#busuanzi_value_site_uv").html(parseInt($("#busuanzi_value_site_uv").html()) +
                    uvcountOffset); // 加上初始数据 
                clearInterval(int);
            }
        }
    });
</script>

<script language=javascript>
    function siteTime() {
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth() + 1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();

        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */

        var t1 = Date.UTC(2019, 08, 10, 00, 00, 00); //北京时间2019-8-1 00:00:00
        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
        var diff = t2 - t1;
        var diffYears = Math.floor(diff / years);
        var diffDays = Math.floor((diff / days) - diffYears * 365);
        var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
        var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) / minutes);
        var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours - diffMinutes *
            minutes) / seconds);
        document.getElementById("sitetime").innerHTML = "本站已勉强运行 " + diffYears + " 年 " + diffDays + " 天 " + diffHours +
            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒" ;
    } /*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
    siteTime();
</script>

<!-- 鼠标点击烟花爆炸效果  洪卫 shw2018 add 2019.09.09 -->


<!-- 在线聊天工具  洪卫 shw2018 add 2019.09.11 -->
<!-- <script src="//code.tidio.co/rwjwdlfhkt9pp7zjsjcva0ug96bvfhss.js"></script> -->

<!-- 代码高亮  洪卫 shw2018 add 2019.09.11 -->
<!-- <script src="/libs/highlight/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script> -->



        <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>
<!-- 洪卫 shw2018 modify 2019.08.30 -->
<script src="/js/search.js"></script>
<!-- <script src="/js/search.js"></script> -->
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
        <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


        <script src="/libs/materialize/materialize.min.js"></script>
        <script src="/libs/masonry/masonry.pkgd.min.js"></script>
        <script src="/libs/aos/aos.js"></script>
        <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
        <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
        <script src="/js/matery.js"></script>

        <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-146860938-1"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', 'UA-146860938-1');
</script>



        
            <script src="/libs/others/clicklove.js"></script>
        

        
            <script async src="/libs/others/busuanzi.pure.mini.js"></script>
        

        <!-- 洪卫 shw2018 add 2019.08.28 -->
        <script type="text/javascript">
            var OriginTitile = document.title,
                st;
            document.addEventListener("visibilitychange", function () {
                document.hidden ? (document.title = "看不见我🙈~看不见我🙈~", clearTimeout(st)) : (document.title =
                    "(๑•̀ㅂ•́) ✧被发现了～", st = setTimeout(function () {
                        document.title = OriginTitile
                    }, 3e3))
            })
        </script>

        <!-- 天气接口控件  洪卫 shw2018 add 2019.09.09 -->
        
            <!-- 天气接口插件  洪卫 shw2018 add 2019.09.09 -->
<style type="text/css">
  #weather-float-he {
    position: absolute;
    z-index: 9999;
    padding: 0px;
    top: 8px;
    left: 8px;
  }
</style>

<script type="text/javascript">
  WIDGET = {
    FID: '1tFpFZ5Mtj'
  }
</script>
<!-- <script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"></script> -->

<script type="text/javascript">
  //只在桌面版网页启用特效
  var windowWidth = $(window).width();
  if (windowWidth > 768) {
    document.write('<script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"><\/script>');
  }
</script>
        

        <!-- 鼠标点击烟花爆炸效果  洪卫 shw2018 add 2019.09.09 -->
        

        <!-- 背景雪花飘落特效洪卫 shw2018 add 2019.09.10 -->
        
            <script type="text/javascript">
            //只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/js/sakura.js"><\/script>');
            }
            </script>
        

        <!-- 鼠标点击文字特效 洪卫 shw2018 add 2019.09.10-->
        

        <!-- 背景雪花飘落特效 洪卫 shw2018 add 2019.09.10 -->
        

        <!-- 在线聊天工具  洪卫 shw2018 add 2019.09.11 -->
        
            <script src="//code.tidio.co/rwjwdlfhkt9pp7zjsjcva0ug96bvfhss.js"></script>
            <!--  在线聊天位置自定义  洪卫 shw2018 add 2019.09.13  -->
            <script> 
                $(document).ready(function () {

                    setInterval(change_Tidio, 50);  
                    function change_Tidio() { 

                        var tidio=$("#tidio-chat iframe");
                        if(tidio.css("display")=="block"&& $(window).width()>977 ){
                            document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" &&$(window).width()>977)>0? "-40px" : ($("div.toc-title").length&&$(window).width()>977)>0?"80px":"20px";   
                            document.getElementById("tidio-chat-iframe").style.right="-15px";   
                            document.getElementById("tidio-chat-iframe").style.height=parseInt(tidio.css("height"))>=520?"520px":tidio.css("height");
                            document.getElementById("tidio-chat-iframe").style.zIndex="997";
                        } 
                        else if(tidio.css("display")=="block"&&$(window).width()>601 &&$(window).width()<992 ){
                            document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && 601< $(window).width()<992)>0? "-40px":"20px" ;   
                            document.getElementById("tidio-chat-iframe").style.right="-15px"; 
                            document.getElementById("tidio-chat-iframe").style.zIndex="997";
                        }
                        else if(tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))<230){
                            document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && $(window).width()<601)>0? "-10px":"45px" ;   
                            document.getElementById("tidio-chat-iframe").style.zIndex="997";
                        }

                        if( tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))>=230){
                            document.getElementById("tidio-chat-iframe").style.zIndex="998";
                        }
                    } 
                }); 
            </script>
        

        <!--  html 预加载脚本  洪卫 shw2018 add 2019.09.12  -->
        <script src="/js/instant.page.js" type="module"></script>

        <!-- 背景 canvas-nest  洪卫 shw 2018  add 2019.09.15-->
        

        <!-- 背景静止彩带  洪卫 shw 2018  add 2019.09.15-->
        

        <!-- 背景动态彩带 洪卫 shw 2018  add 2019.09.15-->
        
            <script type="text/javascript">
            var windowWidth = $(window).width();
            if (windowWidth > 992) {
                document.write('<script type="text/javascript" src="/libs/background/ribbon-dynamic.js"><\/script>');
            }
            </script>
        

        <!-- <script src='https://cdn.jsdelivr.net/gh/fcmam5/nightly.js@v1.0/dist/nightly.min.js'></script> -->

    </body>
</html>